# -*- coding: utf-8 -*-
"""
PBAR_CompareWidthCargoZspecBasicScanImages.py

look at new cargo images and basic scan zspec and see how I can line them up


Created on Wed Apr 30 10:32:12 2014

@author: jkwong
"""

import PBAR_Zspec, PBAR_Cargo
import os
import numpy as np
reload(PBAR_Zspec)
reload(PBAR_Cargo)

dataPath = r'E:\PBAR\data4\BasicScanCargo'
dataPathSW = r'E:\PBAR\data4\BasicScansStandardWidth'

datasetDescription = PBAR_Zspec.ReadCargoDataDescriptionFile(r'E:\PBAR\data4\CargoSet2.txt')

datZspec = []
datRad = []
datZspecSW = []
datRadSW = []

fullFilenameZspec = []
fullFilenameRad = []
fullFilenameZspecSW = []
fullFilenameRadSW = []

filenameZspec = []
filenameRad = []
filenameZspecSW = []
filenameRadSW = []

for i in xrange(20):
    
    # zspec regular and standard width
    filename = '%s-FDFC-All.npy' %datasetDescription['scanID'][i]
    filenameZspecSW.append(filename)
    fullfilename = os.path.join(dataPath, filename)
    fullFilenameZspec.append(fullfilename)
    print('Loading %s' %fullfilename)
    datZspec.append(np.load(fullfilename))
    
    filename = '%s-FDFC-All_SW.npy' %datasetDescription['scanID'][i]
    filenameZspecSW.append(filename)
    fullfilename = os.path.join(dataPathSW, filename)
    fullFilenameZspecSW.append(fullfilename)
    print('Loading %s' %fullfilename)
    datZspecSW.append(np.load(fullfilename))
    
    # cargo/rad regular and standard width
    filename = 'PBAR-%s.cargoimage' %datasetDescription['dataFile'][i]
    filenameRad.append(filename)
    fullfilename = os.path.join(dataPath, filename)
    fullFilenameRad.append(fullfilename)
    print('Loading %s' %fullfilename)
    (A,bpp,formatt,flag,low1,high1,low2,high2) = PBAR_Cargo.ReadCargoImage(fullfilename)
    datRad.append(A)
    
    filename= 'PBAR-%s.cargoimageSW.npy' %datasetDescription['dataFile'][i]
    filenameRadSW.append(filename)
    fullfilename = os.path.join(dataPathSW, filename)
    fullFilenameRadSW.append(fullfilename)
    print('Loading %s' %fullfilename)
    datRadSW.append(np.load(fullfilename))

# Plot sum of counts, all detectors vs time slice
#  - zspec and cargo/rad
#  - standard width 
# - normalized to unit area
# objective - see if everything lining up in standard sized images

plt.figure()
plt.grid()
for i in xrange(len(datZspec)):
   plt.plot(datZspecSW[i][:,:,6:].sum(2).sum(1) / np.float(datZspecSW[i][:,:,5:].sum(2).sum(1).sum()), label = filenameZspecSW[i])

for i in xrange(len(datRad)):
    plt.plot(datRadSW[i].sum(1) / datRadSW[i].sum(1).sum(), label = filenameRadSW[i], linestyle = ':')

plt.legend(prop={'size':8})
plt.xlabel('Slice')
plt.ylabel('Count (Area Normalized to 1)')


MINBIN = 5

index = 14
figure()
plt.imshow(datZspecSW[index][:,:,MINBIN:].sum(2).T, interpolation = 'nearest', aspect='auto', cmap = cm.Greys_r)
plt.title('Zspec: %s' %filenameZspecSW[index])
xlim((600, 750))

figure()
plt.imshow(datRadSW[index].T, interpolation = 'nearest', aspect='auto', cmap = cm.Greys_r)
plt.title('Rad: %s' %filenameRadSW[index])
xlim((600, 750))




#plot sum of counts, all detectors vs time slice

plt.figure()
plt.grid()

for i in xrange(len(datZspec)):
    plt.plot(datZspec[i][:,100:102,4:].sum(2).sum(1), label = 'slices %d' %datZspec[i].shape[0])

plt.legend()
title('Zspec')

plt.figure()
plt.grid()
for i in xrange(len(datRad)):
    plt.plot(datRad[i][:,100:110].sum(1), label = 'slices %d' %datRad[i].shape[0])
plt.legend()
title('Rad')



#plot sum of counts, all detectors vs time slice
# reverse head tail
plt.figure()
plt.grid()
for i in xrange(len(datZspec)):
    plt.plot(np.flipud(datZspec[i][:,100:102,4:].sum(2).sum(1)), label = 'slices %d' %datZspec[i].shape[0])

plt.legend()
title('Zspec')

plt.figure()
plt.grid()
for i in xrange(len(datRad)):
    plt.plot(np.flipud(datRad[i][:,100:110].sum(1)), label = 'slices %d' %datRad[i].shape[0])
plt.legend()
title('Rad')



# SHOW IMAGES FOR STANDARD WIDTH IMAGES
index = 0
figure()
plt.imshow(datZspecSW[index][:,:,5:].sum(2).T, interpolation = 'nearest', aspect='auto', cmap = cm.Greys_r)
plt.title('Zspec; start bin %d' %datZspecStart[index])
#xlim((60, 100))
ylim((0, 60))

figure()
plt.imshow(datRadSW[index].T, interpolation = 'nearest', aspect='auto', cmap = cm.Greys_r)
plt.title('Rad')

#xlim((60, 100))
ylim((0, 60))



## use this array to find the start
detectorList = np.array([31, 32, 33, 34, 35, 36, 37])
detectorList = np.array([31, 34, 35, 36])
lowerBound = 100
upperBound = 400
dat2 = datZspec[0][:,detectorList,:].mean(2).max(1)
dat3 = datZspec[0][:,detectorList,5:].mean(2).mean(1)

threshold = (dat2[lowerBound:upperBound].max() + dat2[lowerBound:upperBound].min())/2.0

threshold3 = (dat3[lowerBound:upperBound].max() + dat3[lowerBound:upperBound].min())/2.0

#    print threshold
cut = (dat2 < threshold) & (np.arange(len(dat2)) > lowerBound) & (np.arange(len(dat2)) < upperBound)
startBin = np.where(cut)[0][0]
#
#cut3 = (dat3 >= threshold) & (np.arange(len(dat3)) > lowerBound) & (np.arange(len(dat3)) < upperBound)
#startBin = np.where(cut3)[0][0]